<template>
  <div class="app-container">
    <YearMonthSelector v-model="queryParams.reportingYearMonth" @change="handleYearMonthChange" />

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学校名称" prop="schoolName">
        <el-input
          v-model="queryParams.schoolName"
          placeholder="请输入学校名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教育性质" prop="educationNature">
        <el-select v-model="queryParams.educationNature" placeholder="请选择教育性质" clearable>
          <el-option
            v-for="dict in education_nature"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学校地址" prop="schoolAddress">
        <el-input
          v-model="queryParams.schoolAddress"
          placeholder="请输入学校地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑面积" prop="buildingArea">
        <el-input
          v-model="queryParams.buildingArea"
          placeholder="请输入建筑面积"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="办学规模" prop="schoolScale">
        <el-input
          v-model="queryParams.schoolScale"
          placeholder="请输入办学规模"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['report:school:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['report:school:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['report:school:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['report:school:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5" v-if="reportStatus === '0'">
        <el-button
          type="success"
          plain
          @click="handleReport"
        >立即上报</el-button>
      </el-col>
      <el-col :span="1.5" v-else>
        <el-button
          type="info"
          plain
          disabled
        >已上报</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="schoolList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="学校名称" align="center" prop="schoolName" />
      <el-table-column label="教育性质" align="center" prop="educationNature">
        <template #default="scope">
          <dict-tag :options="education_nature" :value="scope.row.educationNature"/>
        </template>
      </el-table-column>
      <el-table-column label="学校地址" align="center" prop="schoolAddress" />
      <el-table-column label="建筑面积" align="center" prop="buildingArea" />
      <el-table-column label="办学规模" align="center" prop="schoolScale" />
      <el-table-column label="教学设施" align="center" prop="teachingFacilities" />
      <el-table-column label="教学设备" align="center" prop="teachingEquipment" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="reportStatus === '0'">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['report:school:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['report:school:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学校对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="schoolRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学校名称" prop="schoolName">
          <el-input v-model="form.schoolName" placeholder="请输入学校名称" />
        </el-form-item>
        <el-form-item label="教育性质" prop="educationNature">
          <el-select v-model="form.educationNature" placeholder="请选择教育性质">
            <el-option
              v-for="dict in education_nature"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校地址" prop="schoolAddress">
          <el-input v-model="form.schoolAddress" placeholder="请输入学校地址" />
        </el-form-item>
        <el-form-item label="建筑面积" prop="buildingArea">
          <el-input v-model="form.buildingArea" placeholder="请输入建筑面积" />
        </el-form-item>
        <el-form-item label="办学规模" prop="schoolScale">
          <el-input v-model="form.schoolScale" placeholder="请输入办学规模" />
        </el-form-item>
        <el-form-item label="教学设施" prop="teachingFacilities">
          <el-input v-model="form.teachingFacilities" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="教学设备" prop="teachingEquipment">
          <el-input v-model="form.teachingEquipment" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="School">
import { listSchool, getSchool, delSchool, addSchool, updateSchool } from "@/api/report/school"
import { getMonthlyReportStatusDetail, addReportRecord } from "@/api/report/monthlyReportStatus"
import YearMonthSelector from "@/components/YearMonthSelector/index.vue";

const { proxy } = getCurrentInstance()
const { education_nature } = proxy.useDict('education_nature')

const schoolList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const reportStatus = ref("0") // 默认未上报

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schoolName: null,
    educationNature: null,
    schoolAddress: null,
    buildingArea: null,
    schoolScale: null,
    teachingFacilities: null,
    teachingEquipment: null,
    reportingYearMonth: null
  },
  rules: {
    schoolName: [
      { required: true, message: "学校名称不能为空", trigger: "blur" }
    ],
    educationNature: [
      { required: true, message: "教育性质不能为空", trigger: "change" }
    ],
    schoolAddress: [
      { required: true, message: "学校地址不能为空", trigger: "blur" }
    ],
    buildingArea: [
      { required: true, message: "建筑面积不能为空", trigger: "blur" }
    ],
    schoolScale: [
      { required: true, message: "办学规模不能为空", trigger: "blur" }
    ],
    teachingFacilities: [
      { required: true, message: "教学设施不能为空", trigger: "blur" }
    ],
    teachingEquipment: [
      { required: true, message: "教学设备不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询学校列表 */
function getList() {
  loading.value = true
  // 确保携带 reportingYearMonth 参数
  if (!queryParams.value.reportingYearMonth) {
    const now = new Date()
    queryParams.value.reportingYearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
  }

  // 获取上报状态
  getReportStatus()

  listSchool(queryParams.value).then(response => {
    schoolList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 获取上报状态
function getReportStatus() {
  const tableName = "school"
  const reportYearMonth = queryParams.value.reportingYearMonth
  if (reportYearMonth) {
    getMonthlyReportStatusDetail(tableName, reportYearMonth).then(response => {
      reportStatus.value = response.data.isReported
    }).catch(() => {
      // 如果获取失败，默认为未上报
      reportStatus.value = "0"
    })
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    schoolName: null,
    educationNature: null,
    schoolAddress: null,
    buildingArea: null,
    schoolScale: null,
    teachingFacilities: null,
    teachingEquipment: null,
    reportingYearMonth: queryParams.value.reportingYearMonth
  }
  proxy.resetForm("schoolRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加学校"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getSchool(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改学校"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["schoolRef"].validate(valid => {
    if (valid) {
      // 确保传递 reportingYearMonth 字段
      form.value.reportingYearMonth = queryParams.value.reportingYearMonth;
      if (form.value.id != null) {
        updateSchool(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSchool(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除学校编号为"' + _ids + '"的数据项？').then(function() {
    return delSchool(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('report/school/export', {
    ...queryParams.value
  }, `school_${new Date().getTime()}.xlsx`)
}

/** 上报按钮操作 */
function handleReport() {
  proxy.$modal.confirm('确定要上报数据吗？上报后数据将不可修改！').then(() => {
    const reportData = {
      tableName: "school",
      reportYearMonth: queryParams.value.reportingYearMonth
    }

    return addReportRecord(reportData)
  }).then(response => {
    if (response.data === 1) {
      proxy.$modal.msgSuccess("上报成功")
      // 更新上报状态为已上报
      reportStatus.value = "1"
    } else {
      proxy.$modal.msgError("上报失败")
    }
  }).catch(error => {
    if (error !== 'cancel') {
      proxy.$modal.msgError("上报失败: " + error.message)
    }
  })
}

// 年月选择变化处理
function handleYearMonthChange() {
  getList()
}

getList()
</script>
